<template>
  <el-container class="category-container">
    <!-- 搜索区域 -->
    <el-header>
      <div class="category-search">
        <span style="padding-right: 10px;">知识类别：</span>
        <!-- 绑定-刷新-重置 -->
        <el-input size="small" placeholder="请输入知识大类" v-model="queryInfo.knowCateName" @keyup.enter.native="getCateList"
          clearable @clear="getCateList">
          <el-button size="small" slot="append" icon="el-icon-search" @click="getCateList()"></el-button>
        </el-input>
      </div>
    </el-header>

    <!-- 列表区域 -->
    <el-main>
      <div style="padding-bottom: 10px;">
        <el-button size="small" type="primary" @click="showAddCateDialog"><i class="el-icon-plus"></i>&nbsp;新增</el-button>
      </div>
      <!-- 知识分类数据 -->
      <!-- vue-table-with-tree-grid -->
      <tree-table :data="cateList" :columns="columns" :selection-type="false" :expand-type="false">
        <template slot="opt" slot-scope="scope">
          <el-button size="mini" type="primary" plain icon="el-icon-edit"
            @click="showEditCateDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="primary" plain icon="el-icon-plus"
            @click="showAddLittleDialog(scope.row)">添加子类别</el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete"
            @click="removeCateByID(scope.row)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页功能 -->
      <div style="padding-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum" :page-sizes="[1, 5, 10, 20]" :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

      <!-- 新增知识类别的对话框 -->
      <el-dialog title="新增知识类别" :visible.sync="addCateDialogVisible" width="40%">
        <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateForm" label-width="auto">
          <el-form-item label="知识类别名称" prop="knowCateName">
            <el-input v-model="addCateForm.knowCateName" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类描述" prop="notes">
            <el-input v-model="addCateForm.notes" clearable></el-input>
          </el-form-item>
          <!-- 创建者是否直接引入用户名 -->
          <el-form-item label="创建者" prop="staffCode">
            <el-input v-model="addCateForm.staffCode" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑知识类别的对话框 -->
      <el-dialog title="编辑知识类别" :visible.sync="editCateDialogVisible" width="40%">
        <el-form :model="editCateForm" :rules="addCateFormRules" ref="editCateForm" label-width="auto">
          <el-form-item label="知识id">
            <el-input v-model="editCateForm.cateId" disabled></el-input>
          </el-form-item>
          <el-form-item label="知识类别名称" prop="knowCateName">
            <el-input v-model="editCateForm.knowCateName" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类描述" prop="notes">
            <el-input v-model="editCateForm.notes" clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加子类别的对话框 -->
      <el-dialog title="添加子类别" :visible.sync="addLittleDialogVisible" width="40%">
        <el-form :model="addLittleForm" :rules="addCateFormRules" ref="addLittleForm" label-width="auto">
          <el-form-item label="父类名称">
            <el-input v-model="addLittleForm.parentName" disabled></el-input>
          </el-form-item>
          <el-form-item label="知识类别名称" prop="knowCateName">
            <el-input v-model="addLittleForm.knowCateName" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类描述" prop="notes">
            <el-input v-model="addLittleForm.notes" clearable></el-input>
          </el-form-item>
          <!-- 创建者是否直接引入用户名 -->
          <el-form-item label="创建者" prop="staffCode">
            <el-input v-model="addLittleForm.staffCode" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addLittleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addLittleCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { getAllApi, getSingleByIdApi, cateInsertApi, cateUpdateApi, cateDeleteByIDApi } from '@/api/manageApi'
import { AxiosError } from 'axios'
export default {
  data() {
    return {
      cateList: [],
      // 查询条件
      queryInfo: {
        pageNum: 1, //页码
        pageSize: 5, //每页显示多少条数据
      },
      total: 0,
      columns: [
        {
          label: "知识类别",
          prop: "knowCateName",
        },
        {
          label: "分类描述",
          prop: "notes",
        },
        {
          label: "创建者",
          prop: "staffCode",
        },
        {
          label: "创建时间",
          prop: "createtime",
        },
        {
          label: "操作",
          type: 'template',
          template: 'opt',
        },
      ],
      // todo 新增分类
      addCateDialogVisible: false,
      addCateForm: {
        knowCateName: '',
        notes: ''
      },
      addCateFormRules: {
        knowCateName: [
          { required: true, message: '请输入知识分类名称', trigger: 'blur' }
        ],
      },

      // todo 编辑分类
      editCateDialogVisible: false,
      editCateForm: {},

      // todo 添加子类别
      addLittleDialogVisible: false,
      addLittleForm: {
        parentId: '',
        knowCateName: '',
        notes: ''
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await getAllApi(this.queryInfo);
      // console.log("查询成功");
      this.cateList = res.list.records;
      this.total = res.list.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getCateList();
    },

    //todo 新增分类
    showAddCateDialog() {
      this.addCateDialogVisible = true;
      // ! 创建者暂时设置一个默认值，后续和用户模块绑定
      this.addCateForm.staffCode = '1212';
      if (this.$refs.addCateForm !== undefined) {
        this.$refs.addCateForm.resetFields();
      }
    },
    async addCate() {
      this.$refs.addCateForm.validate(async (valid, field) => {
        if (!valid) {
          let arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        console.log('验证通过');

        const { data: res } = await cateInsertApi(this.addCateForm);
        console.log("新增成功");
        this.addCateDialogVisible = false;
        this.getCateList();
      })
    },

    //todo 编辑分类
    async showEditCateDialog(cateInfo) {
      const { data: res } = await getSingleByIdApi({ knowCateId: cateInfo.knowCateId });

      // console.log("编辑查询成功");
      this.editCateForm = res.single;
      // console.log(this.editCateForm);

      this.editCateDialogVisible = true;
      if (this.$refs.editCateForm !== undefined) {
        this.$refs.editCateForm.resetFields();
      }
    },

    async editCate() {
      this.$refs.editCateForm.validate(async (valid, field) => {
        if (!valid) {
          let arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        console.log('验证通过');
        const { data: res } = await cateUpdateApi({
          knowCateId: this.editCateForm.knowCateId, knowCateName: this.editCateForm.knowCateName, notes: this.editCateForm.notes
        });
        console.log("编辑成功");
        this.editCateDialogVisible = false;
        this.getCateList();
      })
    },

    //todo 添加子类别
    async showAddLittleDialog(cateInfo) {
      const { data: res } = await getSingleByIdApi({ knowCateId: cateInfo.knowCateId });
      // console.log("添加子类别查询成功");
      this.addLittleForm.parentId = res.single.knowCateId;
      this.addLittleForm.parentName = res.single.knowCateName;
      // console.log(this.addLittleForm);

      if (res.single.cateId.length / 2 < 3) {
        this.addLittleDialogVisible = true;
        // ! 创建者暂时设置一个默认值，后续和用户模块绑定
        this.addLittleForm.staffCode = '2323';
        if (this.$refs.addLittleForm !== undefined) {
          this.$refs.addLittleForm.resetFields();
        }
      }
      else {
        this.addLittleDialogVisible = false;
        return this.$message.warning({
          message: "已经是最小类，不能再新增子类！",
          druation: 1500
        })
      }

    },

    async addLittleCate() {
      this.$refs.addLittleForm.validate(async (valid, field) => {
        if (!valid) {
          let arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        console.log('验证通过');
        const { data: res } = await cateInsertApi({
          parentId: this.addLittleForm.parentId, knowCateName: this.addLittleForm.knowCateName, notes: this.addLittleForm.notes,
          staffCode: this.addLittleForm.staffCode
        });
        console.log("添加子类别成功");
        this.addLittleDialogVisible = false;
        this.getCateList();
      })
    },

    //todo 删除分类
    async removeCateByID(cateInfo) {
      let result = await this.$confirm(`确定要删除该条记录？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).catch(reason => reason)

      // 取消删除
      if (result === 'cancel') {
        return this.$message.info({
          message: "已取消删除!",
          druation: 1500
        })
      }

      try {
        const { data: res } = await cateDeleteByIDApi({ knowCateId: cateInfo.knowCateId })
        this.$message.success({
          message: '删除成功!',
          druation: 1000
        })
        this.getCateList()
      } catch (error) {
        if (error.response.data.code == 100) {
          return this.$message.error({
            message: error.response.data.tip,
            druation: 1500
          })
        }
      }
    }

  },
}
</script>

<style lang="less" scoped>
.category-container {
  padding: 15px;
}

//todo 搜索区域
.el-header {
  padding: 0 40px;
  background-color: #fff;

  .category-search {
    display: flex;
    align-items: center;
    height: 60px;
  }

  .el-input {
    width: 300px;
  }
}

//todo 列表区域
.el-main {
  overflow: hidden !important;
  margin-top: 15px;
  background-color: #fff;
}

.el-button--mini {
  padding: 7px 3px;
  font-size: 10px;
}
</style>

<style>
.zk-table {
  color: #5d6880 !important;
  border-color: #e4ebf5 !important;
  border-left-width: 0 !important;
  border-right-width: 0 !important;
}

.zk-table__header-row,
.zk-table__body-row:hover {
  background-color: #f5f7fd !important;
}

.zk-table__cell-inner {
  padding-left: 50px !important;
}
</style>